# -*- coding: utf-8 -*-



## ------------------------------------------------------------
## Copyright 2010 Pierre-Antoine Delsart
## 
## This file is part of LeVin.
## 
## LeVin is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
## 
## LeVin is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## 
## You should have received a copy of the GNU General Public License
## along with LeVin.  If not, see <http://www.gnu.org/licenses/>.
## ---------------------------------------------------------------


# Form implementation generated from reading ui file 'wineBasegui.ui'
#
# Created: Sun Oct 31 15:18:42 2010
#      by: PythonQt UI code generator 4.7.3
#
# WARNING! All changes made in this file will be lost!


from PythonQt import QtCore, QtGui, QtSvg

from qtcommon import tr,WinePixmaps, getIcon, getData, connect
import qtcommon

from PythonQt import QtCore, QtGui
import wineBase
import editWine
import components
import wineDescriptionTab, wineTastingTab , areaWidget
columnContent = [
    ("appellation", tr("Appellation") , 0.4 ),
    ("cru_name", tr("Vintage") , 0.4),
    ("millesime", tr("Vintage year"), -1),
    ("meanrate", tr("Rate"), -1),
    ]


from wineAreas import wineWorld , wineColors
import wineAreas
import wineSelector



class WineFilter(object):
    filtered = set([])

class FilterButton(WineFilter):
    def __init__(self,mainWindow, t):
        self.button  = QtGui.QPushButton(mainWindow.toolBar)
        self.button.setText( t  )
                
        #self.box.addItems(self.items())
        mainWindow.toolBar.addWidget( self.button)
        self.last_index = -1
        self.mainWindow = mainWindow
        connect(self.box, QtCore.SIGNAL("clicked()"), self.filterChanged);

    def filterChanged(self,i):
        index=self.box.currentIndex()
        if self.last_index == index:
            return
        res=self.filter(index)
        self.last_index =index
        if res :
            self.mainWindow.active_filters.add(self)
        else:
            self.mainWindow.active_filters.remove(self)
        self.mainWindow.applyFilter()

    
class FilterComboBox(WineFilter):
    def __init__(self,mainWindow):
        self.box  = QtGui.QComboBox(mainWindow.toolBar)
        self.box.addItems(self.items())
        mainWindow.toolBar.addWidget( self.box)
        self.last_index = -1
        self.box.setCurrentIndex(0)
        self.mainWindow = mainWindow
        connect(self.box, QtCore.SIGNAL("activated(int)"), self.filterChanged);

    def filterChanged(self,i):
        index=self.box.currentIndex()
        if self.last_index == index:
            return
        res=self.filter(index)
        self.last_index =index
        if res :
            self.mainWindow.active_filters.add(self)
        else:
            self.mainWindow.active_filters.remove(self)
        self.mainWindow.applyFilter()

class NumInStockFilter(FilterComboBox):
    def items(self):
        return [ tr("Available"),  tr("No more") ]

    def filter(self, index):
        if index == 0:
            self.filtered = set(  b for b in wineBase.BottleSet if b.numInStock > 0  )
        else:
            self.filtered = set(  b for b in wineBase.BottleSet if b.numInStock == 0  )
        return True
        #print 'NumInStockFilter ',len(self.filtered)

class ColorFilter(FilterComboBox):
        
    def items(self):
        return [ tr("All") ]+ wineColors 
    def filter(self,index):
        if index == 0:
            return False
        c = index-1
        self.filtered = set(  b for b in wineBase.BottleSet if b.color == c  )
        return True

#redBrush = QtGui.QBrush(QtGui.QColor(158,13,8))
redBrush  = QtGui.QBrush(QtGui.QColor(0xA30C00))
greenBrush = QtGui.QBrush(QtGui.QColor(0x38E055))#0x38E055	65E07A
wineColorBrushes = [ redBrush, greenBrush, redBrush ]


class Ui_EditWineButtonBox(object):
    """ A box containing buttons affecting a wine entry.
    There should be one such object in the app. This editWineButtonBox is attached to the main window
    and shared with component.
    """
    mainWindow = None
    def setupUi(self, parent):
        editWine_buttonBox = QtGui.QDialogButtonBox(parent)        
        editWine_buttonBox.setObjectName("editWine_buttonBox")

        
        drinkWine_button = QtGui.QPushButton(editWine_buttonBox)
        #drinkWine_button.setText( tr( "Edit") )
        icon1 = QtGui.QIcon(getIcon("drinkBottle.svg"))
        drinkWine_button.setIcon( icon1  )
        editWine_buttonBox.addButton(drinkWine_button ,QtGui.QDialogButtonBox.YesRole )
        self.drinkWine_button = drinkWine_button

        editWine_button = QtGui.QPushButton(editWine_buttonBox)
        editWine_button.setText( tr( "Edit") )        
        editWine_button.setIcon( qtcommon.app.style().standardIcon(QtGui.QStyle.SP_FileDialogListView)  )
        editWine_buttonBox.addButton(editWine_button ,QtGui.QDialogButtonBox.YesRole )
        self.editWine_button = editWine_button
        

        suppressWineB = QtGui.QPushButton(editWine_buttonBox)
        suppressWineB.setText( tr( "Suppress") )
        suppressWineB.setIcon( qtcommon.app.style().standardIcon(QtGui.QStyle.SP_DialogDiscardButton)  )        
        editWine_buttonBox.addButton(suppressWineB,QtGui.QDialogButtonBox.DestructiveRole)
        self.removeWine_button = suppressWineB

        searchWine_button = QtGui.QPushButton(editWine_buttonBox)
        searchWine_button.setText( tr( "Search") )
        editWine_buttonBox.addButton(searchWine_button ,QtGui.QDialogButtonBox.YesRole )
        self.searchWine_button = searchWine_button

        #verticalLayoutDesc.addWidget(editWine_buttonBox)
        self.editWine_buttonBox = editWine_buttonBox

    def connect(self):
        connect(self.editWine_button , QtCore.SIGNAL("clicked()") ,   self.mainWindow.editBottle)
        connect(self.searchWine_button , QtCore.SIGNAL("clicked()") , self.mainWindow.searchWine)
        connect(self.removeWine_button , QtCore.SIGNAL("clicked()") , self.mainWindow.removeWine)
        connect(self.drinkWine_button , QtCore.SIGNAL("clicked()") ,   self.mainWindow.drinkBottle)
    
            
class Ui_MainWindow(object):
    filters=set([])
    active_filters = set([])
    addTastingDialog = None
    componentList = components.ComponentList( [wineDescriptionTab.WineDescriptionTab(),
                                               wineTastingTab.WineTastingTab() ,
                                               areaWidget.AreaWidget()] )

    wineDescComponent = componentList[ 0 ]
    wineTastingComponent = componentList[ 1 ]
    areaWidget = componentList[2]

    editWineButtonBox = Ui_EditWineButtonBox()
    
    DEFAULTSIZE = (1100, 800)
    DEFAULTWITDTH = DEFAULTSIZE[0]
    
    def setupUi(self, windowWidget):
        equipAreaClasses()
        windowWidget.resize( *self.DEFAULTSIZE )
        components.Component.mainWindow = self        
        Ui_EditWineButtonBox.mainWindow = self
        self.windowWidget = windowWidget
        self.centralwidget = QtGui.QWidget(windowWidget)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.splitter = QtGui.QSplitter(self.centralwidget)
        self.splitter.setOrientation(QtCore.Qt.Horizontal)
        self.splitter.setObjectName("splitter")
        self.treeWidget = QtGui.QTreeWidget(self.splitter)


        self.treeWidget.setObjectName("treeWidget")

        wineAreas.WorldArea.topTreeItem = self.treeWidget.invisibleRootItem ()
        self.treeWidget.setColumnCount(len(columnContent))


        self.fillTree()

        self.rightSideWid = QtGui.QFrame(self.splitter)
        self.rightSideLayout = QtGui.QVBoxLayout(self.rightSideWid)


        self.verticalLayout.addWidget(self.splitter)
        windowWidget.setCentralWidget(self.centralwidget)


        self.toolBar = QtGui.QToolBar(windowWidget)

        self.toolBar.setObjectName("toolBar")
        windowWidget.addToolBar(QtCore.Qt.ToolBarArea(QtCore.Qt.TopToolBarArea), self.toolBar)
        self.toolBar.setMinimumSize(QtCore.QSize(0, 70))

        # --
        icon1 = QtGui.QIcon(getIcon("addBottle.svg"))
        self.addBottle_action = QtGui.QAction(windowWidget)
        self.addBottle_action.setIcon(icon1)    
        self.addBottle_action.setObjectName("addBottle_action")
        self.addBottle_action.setToolTip( tr("Add Wine") )
        self.toolBar.addAction(self.addBottle_action)

        
        self.toolBar.addSeparator()
        
        self.hierarchylist_action = QtGui.QAction(windowWidget)
        self.noHierarchyIcon = QtGui.QIcon(getIcon("noHierarchyList.png"))
        self.hierarchyIcon = QtGui.QIcon(getIcon("hierarchyList.png"))
        self.hierarchylist_action.setIcon(  self.noHierarchyIcon )
        self.hierarchylist_action.setToolTip( tr("No region sorting") )
        self.toolBar.addAction(self.hierarchylist_action)

        self.toolBar.addSeparator()

        self.wineSelector = wineSelector.SelectorManager()
        self.wineSelector.setup( self)

        ## filterLabel = QtGui.QLabel("<b>"+tr("Filters : ")+"</b>",self.toolBar)
        ## self.toolBar.addWidget( filterLabel)

        ## self.filters.add(ColorFilter(self) )
        ## self.filters.add(NumInStockFilter(self) )

        ## self.numWineLabel = QtGui.QLabel("",self.toolBar)
        ## self.toolBar.addWidget( self.numWineLabel)



        ## for f in self.filters:
        ##     if f.filter(0):
        ##         self.active_filters.add(f)
                
        ## self.applyFilter()
        ## print self.active_filters

        self.treeWidget.setAllColumnsShowFocus(True) # avoid dashed column selection
        self.treeWidget.setSortingEnabled(True)
        self.treeWidget.setIndentation(2)

        self.treeWidget.expandAll()

        self.bottleDialog = editWine.getEditWineUI()
        self.bottleDialog.setupUi( QtGui.QDialog() )


        self.editWineButtonBox.setupUi(windowWidget)
        self.componentList.setup()


        # self.tabWidget.setCurrentIndex(0)

        self.componentList.connect()
        self.editWineButtonBox.connect()
        
        wineAreas.CountryArea.bgBrush = QtGui.QBrush(QtGui.QPixmap( getIcon("cbanner.png")))    
        self.retranslateUi(windowWidget)

        #connect(self.treeWidget, QtCore.SIGNAL("itemClicked(QTreeWidgetItem*, int)") , self.toggleExpand)
        connect(self.treeWidget, QtCore.SIGNAL("itemSelectionChanged()") , self.rowSelected)

        connect(self.addBottle_action, QtCore.SIGNAL("triggered()"), self.addBottle);

        self.hierarchyOn = True
        connect(self.hierarchylist_action, QtCore.SIGNAL("triggered()"), self.toggleHierarchy);
        self.rowSelected()
        #self.areaWidget.


    def removeWine(self):
        try:
            row = self.treeWidget.selectedItems()[0]
            b = row.bottle
        except:
            return
        dialog = QtGui.QMessageBox( self.windowWidget)
        dialog.setWindowTitle(  tr("Remove Wine ?") )
        dialog.addButton(QtGui.QMessageBox.Cancel)
        dialog.addButton( QtGui.QMessageBox.Ok )
        dialog.setText(tr( "Suppress  %1 ?").arg(b.cru_name)) 
        res=dialog.exec_()
        if res != QtGui.QMessageBox.Ok:
            return

        row.area.item.removeChild( row)
        b.delete()
        wineBase.db.commit()
        del row

    def searchWine(self):
        row = self.treeWidget.selectedItems()[0]
        b = row.bottle
        url=qtcommon.webSearchUrl(b.appellation, b.cru_name)
        qtcommon.openUrl( url )


    def applyFilter(self):
        filters = set(self.active_filters        )
        if filters == set():
            for b in wineBase.BottleSet:
                b.transiant.row.setHidden(False)
            return
        visible = filters.pop().filtered
        for f in filters:
            visible = visible.intersection(f.filtered)
        for b in wineBase.BottleSet:
            b.transiant.row.setHidden(True)            
        nbottles = 0
        for b in visible:
            b.transiant.row.setHidden(False)            
            nbottles += b.numInStock
        self.numWineLabel.setText( "<b>"+ tr("%1 Bottles / %2 wines ").arg(nbottles).arg(len(visible) )+"</b>")

        

        
    def bottleChanged(self,b):
        self.setupRow(b)
        self.rowSelected()
        

    def currentRow(self):
        try:
            return self.treeWidget.selectedItems()[0]
        except:
            return self.treeWidget.topLevelItem(0)

    def editBottle(self):
        row = self.treeWidget.selectedItems()[0]
        b = row.bottle
        self.bottleDialog.updateFromWine( b )
        res = self.bottleDialog.execDialog(editMode=True,editedB=b)
        if not res :
            return res

        # update the row/area
        area = wineWorld[b.country][b.region]
        if area != row.area:
            row.area.item.removeChild( row )
            row.area = area
            if area.item is None :
                area.createTreeItem( b)
            
            area.item.addChild( row )
        self.setupRow( b ) 
        self.rowSelected()


    def drinkBottle(self):
        row = self.currentRow()
        
        b = row.bottle
        
        self.wineTastingComponent.current_row = row
        
        self.wineTastingComponent.addTasting()
        self.rowSelected()        
        b.numInStock = b.numInStock -1
        wineBase.db.commit()


    def addBottle(self):
        # update the country/region boxes
        w = self.bottleDialog.country_entry.qtelt
        w.setCurrentIndex(w.findText('France'))        
        self.bottleDialog.country_entry.updateSubArea()
        # start the dialog :
        res = self.bottleDialog.execDialog(editMode=False)            
        for b in self.bottleDialog.last_bottle:            
            area = wineWorld[b.country][b.region]
            regItem = area.createTreeItem(b)
            row = QtGui.QTreeWidgetItem(regItem)
            b.transiant.row = row
            row.bottle = b
            row.area = area
            row.selectedFunc = self.wineRowSelected
            self.setupRow( b)
        self.rowSelected()        
        #row.setData( )

        
    def fillTree(self):

        wineAreas.RegionArea.selectedFunc = self.regionRowSelected
        wineAreas.CountryArea.selectedFunc = self.countryRowSelected
        
        allBottles = list(wineBase.BottleSet)
        for (i,b) in enumerate(wineBase.BottleSet):
            area = wineWorld[b.country][b.region]
            #print 'adding ',i,b,area.name
            regItem = area.createTreeItem(b)
            row = QtGui.QTreeWidgetItem(regItem)
            b.transiant.row = row            
            row.bottle = b
            row.area = area
            row.selectedFunc = self.wineRowSelected
            row.setHidden( b.numInStock == 0)
        
        #row.setData( )

    def toggleHierarchy(self):
        if self.hierarchyOn:
            self.toggleHierarchyOff()
        else:
            self.toggleHierarchyOn()

    def toggleHierarchyOff(self):
        topTreeItem = self.treeWidget.invisibleRootItem ()        
        for b in wineBase.BottleSet:
            row=b.transiant.row
            p =  row.parent()
            p.removeChild(row)
            topTreeItem.addChild( row )
            p.setHidden(True)
            p.parent().setHidden(True)
        self.hierarchyOn = False
        self.hierarchylist_action.setIcon( self.hierarchyIcon)
        self.hierarchylist_action.setToolTip( tr("Sort by region") )
        
    def toggleHierarchyOn(self):
        topTreeItem = self.treeWidget.invisibleRootItem ()
        for b in wineBase.BottleSet:
            row=b.transiant.row
            #print row, row.area , row.area.item
            p =  row.area.item
            topTreeItem.removeChild(row)
            p.addChild( row )
            p.setHidden(False)
            p.parent().setHidden(False)
        self.hierarchyOn = True
        self.hierarchylist_action.setIcon( self.noHierarchyIcon)
        self.hierarchylist_action.setToolTip( tr("No region sorting") )
        
    def toggleExpand(self,i,b):
        i.setExpanded( not i.isExpanded() )

    def rowSelected(self):
        row = self.currentRow()
        row.selectedFunc(row)        

        
    def countryRowSelected(self,row):        
        self.componentList.countryRowSelected(row)

    def regionRowSelected(self,row):
        self.componentList.regionRowSelected(row)
    def wineRowSelected(self,row):
        self.componentList.wineRowSelected(row)

    def createDescTab(self):

        pass


    def resizeColumns(self):
        self.treeWidget.resizeColumnToContents(0)
        self.treeWidget.resizeColumnToContents(1)
        #sizeTW = 2.1* sum( self.treeWidget.columnWidth(i) for i in (0,1) )
        #sizeTW = 
        self.splitter.setSizes( [self.DEFAULTWITDTH *3./5. , self.DEFAULTWITDTH*2./5.] )
        
    def setupRow(self, b):

        ratepos = self.ratepos
        brow=b.transiant.row
        brow.area.setupTreeItem(b)            
        for i,(att,d,s) in enumerate(columnContent[:-1]):
            v = getattr(b,att)
            brow.setText( i ,  v if v else "") 
            #if b.color == ''
            brow.setForeground( i, wineColorBrushes[b.color] )
        # set pixmap :
        v = getattr(b,'meanrate')
        if v is None :
            brow.setData(ratepos,QtCore.Qt.DecorationRole, WinePixmaps.noratePix_small)
            #brow.setTextColor( ratepos, brow.backgroundColor(ratepos) ) # PythonQt incomp !!
            brow.setText( ratepos,'-' )
        else:
            v=int(v)
            brow.setData(ratepos,QtCore.Qt.DecorationRole, WinePixmaps.pixRates_small[v])
            brow.setText( ratepos,str(v) )
            #brow.setIcon(ratepos,QtGui.QIcon('ratingGlasess0.svg'))

    def retranslateUi(self, windowWidget):

        self.componentList.retranslate()
        
        windowWidget.setWindowTitle("LeVin" )
        treeheader = self.treeWidget.headerItem()
        for i,c in enumerate(columnContent):
            treeheader.setText(i,c[1] )            
        __sortingEnabled = self.treeWidget.isSortingEnabled()
        self.treeWidget.setSortingEnabled(False)

        self.ratepos = len(columnContent)-1
        WinePixmaps.setup()
        for (i,b) in enumerate(wineBase.BottleSet):
            self.setupRow(b)

        self.treeWidget.setSortingEnabled(__sortingEnabled)


    def resetRateTextColor(self):
        ratepos = len(columnContent)-1
        #bgcolor = self.treeWidget.palette().background().color()
        bgcolor = self.treeWidget.palette().color(QtGui.QPalette.Window)
        for b in wineBase.BottleSet:
            #b.transiant.row.setTextColor( ratepos,bgcolor)
            b.transiant.row.foreground(ratepos).setColor( bgcolor)

    def postShow(self):
        wineAreas.CountryArea.fgBrush = self.testLab.palette().foreground()
        wineAreas.CountryArea.font    = self.testLab.font()
        wineWorld.setSubStyles()

    def bla(self):
        pass






class RowWidgetArea(object):
    """Meant to equip Area classes with code to deal with their row-widget representation """
    spanRow = True
    bgBrush = None #QtGui.QBrush(QtGui.QPixmap("cbanner.png"))
    selectedFunc = None
    item = None
    isSetup = False
    
    def createTreeItem(self, bott):
        if self.item:
            return self.item

        pItem = self.parentArea.createTreeItem(bott)
        #print self.__class__,self.name, ' got parent ',pItem
        item = QtGui.QTreeWidgetItem(pItem)
        self.item = item
        item.area = self
        item.selectedFunc = self.__class__.selectedFunc
        return item

    def setupTreeItem(self,bott):
        if self.isSetup:            
            return
        self.parentArea.setupTreeItem(bott)
        a = getattr(bott , self.attributeInDB)
        item = self.item
        if a :
            item.setText(0, a)
        item.setFirstColumnSpanned(self.spanRow)
        item.setFont(0,self.font)
        item.setForeground( 0,self.fgBrush)
        if self.bgBrush : item.setBackground( 0,self.bgBrush)        
        item.setTextAlignment(0,4)        
        self.isSetup = True

    def setStyle(self):
        self.item.setFont(0,self.font)
        self.item.setForeground( 0,self.fgBrush)
        self.item.setBackground( 0,self.bgBrush)
        
    def setSubStyles(self):
        for a in self.subAreas():
            a.setSubStyles()
        self.setStyle()

    def makeWritable(self):
        self.item = None
        self.isSetup = False
        #print 'makeWritable ',self.name
        for i in self.subAreas():
            i.makeWritable()


def equipAreaClasses():
    # add RowWidgetArea to base class
    wineAreas.Area.__bases__ = (RowWidgetArea, ) + wineAreas.Area.__bases__

    font = QtGui.QFont()
    font.setFamily("Kerkis")
    font.setPointSize(22)
    wineAreas.CountryArea.font = font 
    wineAreas.CountryArea.fgBrush = QtGui.QBrush(QtGui.QColor( 0, 0,0))


    font = QtGui.QFont()
    font.setFamily("Kerkis")
    font.setPointSize(18)

    wineAreas.RegionArea.font = font
    wineAreas.RegionArea.fgBrush = QtGui.QBrush(QtGui.QColor( 0, 0,0))
    wineAreas.RegionArea.bgBrush = None
